package com.hmall.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import com.hmall.item.service.impl.ItemService;
import com.sun.glass.ui.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    @GetMapping("/list")
    public PageDTO list(Integer page,Integer size){
        IPage<Item> page1 = new Page<Item>(page,size);
        itemService.page(page1);
        return new PageDTO(page1.getTotal(),page1.getRecords());
    }
    @GetMapping("/{id}")
    public Item getById(@PathVariable Integer id){
        return  itemService.getById(id);
    }
    @PostMapping
    public void save(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
    }
    @PutMapping("/status/{id}/2")
    public void underCarriage(@PathVariable Integer id){
        Item item = itemService.getById(id);
        item.setStatus(2);
        itemService.updateById(item);
    }
    @PutMapping("/status/{id}/1")
    public void upCarriage(@PathVariable Integer id){
        Item item = itemService.getById(id);
        item.setStatus(1);
        itemService.updateById(item);
    }
    @PutMapping
    public void update(@RequestBody Item item){
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id){
        Item item = itemService.getById(id);
        if(item.getStatus()==1){
            throw new RuntimeException("该商品未下架，请先下架!");
        }
        itemService.removeById(id);
    }
}

